<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索 -->
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="请输入会员卡名"
            clearable
            v-model="listQuery.name"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            size="small"
            v-model="listQuery.retailer_id"
            clearable
            placeholder="请选择商家"
          >
            <el-option
              v-for="item in retailers"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleFilter"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table
        style="width: 100%"
        v-loading="listLoading"
        border
        fit
        stripe
        highlight-current-row
        size="small"
        :data="datas"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="#" align="center" type="selection">
        </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :label="column.title"
          :prop="column.key"
          :key="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getRetailerCardList"
      />
      <!-- 分页 end -->
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="700px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="padding: 0 30px"
        size="small"
      >
        <el-form-item label="商家名称" prop="retailer">
          <el-select
            v-model="form.retailer"
            clearable
            placeholder="请选择商家名称"
          >
            <el-option
              v-for="item in retailers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员卡" prop="card">
          <el-select
            v-model="form.card"
            placeholder="会员卡"
            clearable
            @change="selectChange"
          >
            <el-option
              v-for="item in cards"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
              <span style="float: left"
                >{{ item.name }}({{ item.amount }})</span
              >
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.retailer_name
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="折扣率" prop="discount">
          <el-input v-model="form.discount" placeholder="折扣率" clearable>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="form.count" placeholder="数量" clearable>
            <el-button slot="append">张</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="使用说明" prop="comment">
          <el-input v-model="form.comment" placeholder="使用说明" clearable />
        </el-form-item>
        <el-form-item label="商家确认" prop="ack">
          <el-select v-model="form.ack" clearable placeholder="商家确认">
            <el-option
              v-for="item in acks"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSave()" size="small"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getAllRetailer } from "@/api/member";
import {
  getRetailerCards,
  addRetailerCard,
  updateRetailerCard,
  delRetailerCard,
  delRetailerCards,
  getAllCards,
} from "@/api/card";

const defaultForm = {
  id: null,
  card: null,
  retailer: null,
  count: null,
  discount: null,
  comment: null,
  ack: null,
};

export default {
  name: "RetailerCard",
  data() {
    return {
      title: "商家会员卡",
      form: Object.assign({}, defaultForm),

      formRules: {
        card: [{ required: true, message: "请选择会员卡", trigger: "blur" }],

        retailer: [{ required: true, message: "请选择商家", trigger: "blur" }],
        count: [{ required: true, message: "请输入数量", trigger: "blur" }],
        comment: [
          { required: true, message: "请输入使用说明", trigger: "blur" },
        ],
      },
      total: 0,
      datas: [],
      retailers: [],
      cards: [],
      selections: [],
      listLoading: true,

      dialogType: "new",
      dialogVisible: false,

      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        retailer_id: null,
      },
      acks: [
        { value: 0, label: "待确认" },
        { value: 1, label: "已确认" },
      ],
      tableColumns: [
        {
          key: "card_name",
          title: "会员卡名称",
          align: "center",
        },
        {
          key: "retailer_name",
          title: "商家名称",
          align: "left",
        },
        {
          key: "amount",
          title: "面额(元)",
          align: "center",
          width: "100px",
        },
        {
          key: "discount",
          title: "折扣率(%)",
          align: "center",
          width: "100px",
        },
        {
          key: "count",
          title: "数量(张)",
          align: "center",
          width: "100px",
        },
        {
          key: "ack_name",
          title: "是否确认",
          align: "center",
          width: "100px",
        },
        {
          key: "comment",
          title: "使用说明",
          align: "center",
        },
      ],
    };
  },
  components: {
    Pagination,
  },
  computed: {
    getTitle() {
      return this.edit ? `修改${this.title}` : `增加${this.title}`;
    },
  },
  created() {
    this.getRetailerCardList();
    this.getCards();
    this.getRetailers();
  },
  methods: {
    getRetailerCardList() {
      this.listLoading = true;
      getRetailerCards(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.total = res.count;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
          this.$message.error("获取数据失败!");
        });
    },
    //获取商家
    getRetailers() {
      getAllRetailer()
        .then((res) => {
          this.retailers = res;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取卡
    getCards() {
      getAllCards()
        .then((res) => {
          this.cards = res;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    handleFilter() {
      this.listQuery.page = 1;
      this.getRetailerCardList();
    },

    selectChange(value) {
      const card = this.cards.find((v) => v.id == value);
      this.form.comment = card.comment;
    },

    //添加数据,弹框显示
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);

      this.dialogType = "edit";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;

        if (this.dialogType == "edit") {
          res = await updateRetailerCard(this.form);
        } else {
          res = await addRetailerCard(this.form);
        }

        this.getRetailerCardList();

        const { card_name, retailer_name, count } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>会员卡名称: ${card_name}</div>
              <div>所属商家: ${retailer_name}</div>
              <div>数量: ${count}</div>
            `,
          type: "success",
        });
        this.dialogVisible = false;
      });
    },

    //删除数据
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delRetailerCard(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delRetailerCards(sel_ids);
          this.getRetailerCardList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },
  },
};
</script>

<style lang="scss" scoped>
.item {
  margin-top: 8px;
}
</style>